package cn.edu.nwsuaf.examcenter.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
/****
 * 文件操作
 * @author 丁成文
 * @version 1.0
 *
 */
public class FileTools {
	
	private static String basePath;
	/***
	 * 静态代码块获取properties文件加载文件保存的根目录
	 */
	
	static{
		Properties prop = new Properties();
		InputStream is = null;
		try {
			is = FileTools.class.getClassLoader().getResourceAsStream("fileconfig.properties");
			prop.load(is);
			basePath = prop.getProperty("basePath").trim();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	/****
	 * 保存文件
	 * @param inputStream 文件流
	 * @param savePath 保存路径
	 * @param fileName 文件名
	 * @return
	 */
	public static boolean saveFile(InputStream inputStream, String savePath,String fileName){
		boolean result = false;
		File file = new File(basePath+savePath);
		FileOutputStream fos = null;
		if(!file.exists()){//判断路径是否存在，若不存在，则新建路径
			file.mkdirs();
		}
		try{//写入文件
			fos=new FileOutputStream(new File(basePath+savePath+"/"+fileName));
			byte[] buffer = new byte[1024*1024];
			int len = 0;
		
			while((len = inputStream.read(buffer))!=-1){
                fos.write(buffer, 0, len); 
                
			}
			fos.flush();
			fos.close();
			result = true;
		}catch(Exception e){
			e.printStackTrace();
		}
		return result;
	}
	
	/****
	 * 单个文件删除
	 * @param filePath 文件路径
	 * @return
	 */
	public static boolean clearFile(String filePath){
		boolean result = false;
		File file = new File(basePath+filePath);
		if(file.exists()){
			result = file.delete();
		}
		return result;
	}
	public static boolean clearFile(File file){
		boolean result = false;
		if(file.exists()){
			result =  file.delete();
		}
		return result;
	}
	/****
	 * 批量删除文件
	 * @param filePathList
	 * @return
	 */
	public static boolean batchClearFiles(List<String> filePathList){
		boolean result = false;
		for(String filePath:filePathList){
			File file = new File(basePath+filePath);
			if(file.exists()){
				result = file.delete();
			}
		}
		return result;
	}
	
	/****
	 * 清空文件夹文件
	 * @param folderPath 文件夹相对路径
	 * @return boolean
	 */
	public static boolean clearFolder(String folderPath){
		boolean result = false;
		File file = new File(basePath+folderPath);
		if(file.exists()){
			File[] files = file.listFiles();
			for(File f:files){
				result = f.delete();
			}
		}
		return result;
	}
	
	/****
	 * 获取根目录
	 * @return 根目录地址
	 */
	public static String getBasePath(){
		return basePath;
	}
}
